package com.ruoyi.common.utils;

import okhttp3.*;

import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * HTTP请求工具类
 * @Author: JH-Ahua
 * @CreateTime: 2025/1/15
 */
public class HttpUtils {
    
    
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .followRedirects(true)
            .followSslRedirects(true)
            .build();
    
    /**
     * 发送GET请求
     * @param url 请求URL
     * @param headers 请求头
     * @return 响应内容
     */
    public static String get(String url, Map<String, String> headers) throws IOException {
        Request.Builder requestBuilder = new Request.Builder().url(url);
        
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        
        Request request = requestBuilder.build();
        
        try (Response response = client.newCall(request).execute()) {
            if (response.body() != null) {
                return response.body().string();
            }
            return "";
        }
    }
    
    /**
     * 发送GET请求（无请求头）
     * @param url 请求URL
     * @return 响应内容
     */
    public static String get(String url) throws IOException {
        return get(url, null);
    }
    
    /**
     * 获取重定向后的最终URL
     * @param url 原始URL
     * @param headers 请求头
     * @return 最终URL
     */
    public static String getFinalUrl(String url, Map<String, String> headers) throws IOException {
        Request.Builder requestBuilder = new Request.Builder().url(url);
        
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        
        Request request = requestBuilder.build();
        
        try (Response response = client.newCall(request).execute()) {
            return response.request().url().toString();
        }
    }
    
    /**
     * 获取重定向后的最终URL（无请求头）
     * @param url 原始URL
     * @return 最终URL
     */
    public static String getFinalUrl(String url) throws IOException {
        return getFinalUrl(url, null);
    }
    
    /**
     * 发送POST请求
     * @param url 请求URL
     * @param headers 请求头
     * @param body 请求体
     * @return 响应内容
     */
    public static String post(String url, Map<String, String> headers, String body) throws IOException {
        RequestBody requestBody = RequestBody.create(
                body != null ? body : "", 
                MediaType.parse("application/json; charset=utf-8")
        );
        
        Request.Builder requestBuilder = new Request.Builder()
                .url(url)
                .post(requestBody);
        
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        
        Request request = requestBuilder.build();
        
        try (Response response = client.newCall(request).execute()) {
            if (response.body() != null) {
                return response.body().string();
            }
            return "";
        }
    }
    
    /**
     * 检查URL是否有效
     * @param url URL字符串
     * @return 是否有效
     */
    public static boolean isValidUrl(String url) {
        try {
            new URL(url);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
